package com.woniu.zsd.merchant.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.woniu.client.PermissionClient;
import com.woniu.dto.CompanyContactDto;
import com.woniu.dto.CompanyDto;
import com.woniu.form.UpdateCompanyForm;
import com.woniu.zsd.merchant.entity.Company;
import com.woniu.zsd.merchant.mapper.CompanyMapper;
import com.woniu.zsd.merchant.service.ICompanyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-27
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements ICompanyService {
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private PermissionClient permissionClient;
    @Override
    public CompanyDto adminFindCompany() {
        Company company = companyMapper.selectById(1);
        CompanyDto companyDto = new CompanyDto();
        BeanUtil.copyProperties(company, companyDto);
        // 将公司联系方式从 JSON 字符串转换为 List<CompanyContactDto>
        String companyContactJson = company.getCompanyContact();
        List<CompanyContactDto> companyContactDtos = JSONUtil.toList(companyContactJson, CompanyContactDto.class);
        companyDto.setCompanyContacts(companyContactDtos);
        return companyDto;
    }

    @Override
    public void updateCompany(UpdateCompanyForm updateCompanyForm, Integer adminId) {
        // 判断手机号是否为公司员工手机号

        Company company = new Company();
        BeanUtil.copyProperties(updateCompanyForm, company);
        // 将公司联系方式从 List<CompanyContactDto> 转换为 JSON 字符串
        String companyContactJson = JSONUtil.toJsonStr(updateCompanyForm.getCompanyContact());
        company.setUpdateUserId(adminId)
               .setCompanyContact(companyContactJson);
        // 通过 adminId 获取修改人姓名
        Set<Integer> adminIds = new HashSet<>();
        adminIds.add(adminId);
        String name = permissionClient.selectAdminInfoByIds(adminIds).getData().get(0).getName();
        company.setUpdateUserName(name);
        companyMapper.updateById(company);
    }

}
